package org.embedchat.protocol.message.server;

import java.util.ArrayList;
import java.util.List;

import org.embedchat.protocol.message.AbstractMessage;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * Room list message format: 
 * 	commandId - short
 * 	bodyLength - uint
 * 	roomsCount - uint
 * than loop for rooms:
 * 	roomId = uint;
 * 	roomName = utf;
 * @author koba
 *
 */
public class RoomsListMessage extends AbstractMessage {

	private static final long serialVersionUID = -2939813916795216587L;
	private List<RoomDescription> rooms = new ArrayList<RoomDescription>();
	
	public List<RoomDescription> getRooms() {
		return rooms;
	}

	public void addRoom(int roomId, String roomName) {
		rooms.add(new RoomDescription(roomId, roomName));
	}

	public int getRoomsCount() {
		return rooms.size();
	}

	@Override
	public int getMessageBodyLength() {
		int length = 2;
		for (RoomDescription desc : rooms) {
			length += desc.getDescriptionMessageLength();
		}
		return length;
	}

	@Override
	public String toString() {
		return new ToStringBuilder(this).append("rooms", rooms).toString();
	}

	@Override
	public boolean equals(final Object other) {
		if (!(other instanceof RoomsListMessage))
			return false;
		RoomsListMessage castOther = (RoomsListMessage) other;
		return new EqualsBuilder().append(rooms, castOther.rooms).isEquals();
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(rooms).toHashCode();
	}

	public class RoomDescription {
		
		private int roomId;
		private String roomName;
		
		public RoomDescription(int roomId, String roomName) {
			this.roomId = roomId;
			this.roomName = roomName;
		}
		
		public int getRoomId() {
			return roomId;
		}
		public void setRoomId(int roomId) {
			this.roomId = roomId;
		}
		public String getRoomName() {
			return roomName;
		}
		public void setRoomName(String roomName) {
			this.roomName = roomName;
		}
		
		public int getDescriptionMessageLength() {
			return 2 + roomName.getBytes().length;
		}
		
		@Override
		public String toString() {
			return new ToStringBuilder(this).append("roomId", roomId).append(
					"roomName", roomName).toString();
		}
		@Override
		public boolean equals(final Object other) {
			if (!(other instanceof RoomDescription))
				return false;
			RoomDescription castOther = (RoomDescription) other;
			return new EqualsBuilder().append(roomId, castOther.roomId).append(
					roomName, castOther.roomName).isEquals();
		}
		@Override
		public int hashCode() {
			return new HashCodeBuilder().append(roomId).append(roomName)
					.toHashCode();
		}
	}
}
